package com.mc.moring.main.fragment

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.provider.Settings
import android.text.Html
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.fastjson.JSONException
import com.axsy.ddoo.bean.ProductInfo
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.mc.moring.BafBase.BAFBaseFragment
import com.mc.moring.R
import com.mc.moring.app.LogUtils
import com.mc.moring.base.HttpCallback
import com.mc.moring.base.SaveZiLiPageTool
import com.mc.moring.bean.AppConfigBean
import com.mc.moring.bean.AppConfigBeanData
import com.mc.moring.bean.BannerDataBean
import com.mc.moring.bean.BeannerData
import com.mc.moring.bean.CreditApplyBean
import com.mc.moring.bean.CreditGetResultBean
import com.mc.moring.bean.DataBean
import com.mc.moring.bean.HomePageCreditInfo
import com.mc.moring.bean.LastLoanDetailBean
import com.mc.moring.bean.LoanInfoVo
import com.mc.moring.bean.LoanInfoVoChild
import com.mc.moring.bean.MyLoanListBean
import com.mc.moring.bean.ProductInfoBean
import com.mc.moring.bean.StationMessageListBean
import com.mc.moring.bean.UnReadBean
import com.mc.moring.bean.WebLinkBean
import com.mc.moring.bean.ZiLiPageUserDataBean
import com.mc.moring.bean.baseBean.BaseBean
import com.mc.moring.event.UpdateLoanBean
import com.mc.moring.event.UpdateLoanEvent
import com.mc.moring.event.UpdateUserEvent
import com.mc.moring.information.CapitalInforActivity
import com.mc.moring.information.modle.KycModle
import com.mc.moring.login.LoginActivity
import com.mc.moring.main.MainActivity
import com.mc.moring.main.MsgActivity
import com.mc.moring.main.WebViewActivity
import com.mc.moring.main.loan.MLoanActivity
import com.mc.moring.main.loan.MPayLoanActivity
import com.mc.moring.main.modle.LoanModle
import com.mc.moring.main.modle.MianModle
import com.mc.moring.main.modle.PermisosModle
import com.mc.moring.main.modle.PermisosModle.Companion.instant
import com.mc.moring.network.HttpResult
import com.mc.moring.util.DateFormatUtils
import com.mc.moring.util.GsonUtils
import com.mc.moring.util.GsonUtils.getGson
import com.mc.moring.util.PointMgr
import com.mc.moring.util.SPUtils
import com.mc.moring.util.ScreenUtil
import com.mc.moring.util.SharePreUtil
import com.mc.moring.util.StringUtils
import com.mc.moring.util.TimeUtils
import com.mc.moring.util.ZhiliDeviceUtils
import com.mc.moring.util.ext.StringExt.extFormatMoney
import com.mc.moring.util.ext.ViewExt.extClickLimit
import com.mc.moring.widge.JDialogCallback
import com.mc.moring.widge.MarkDialog
import com.mc.moring.widge.MyDialog
import com.mc.moring.widge.TipsDialog
import com.mc.moring.widge.TipsPerDialog
import com.mc.moring.widge.TipsPerLineDialog
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.util.Calendar
import java.util.Date


/**
 *
 * @ProjectName:    Monicash
 * @Package:        com.moring.moring.main.fragment
 * @ClassName:      HomeNewFragment
 * @Author:         ANWEN
 * @CreateDate:     2024/1/20 19:17
 * @UpdateUser:
 * @UpdateDate:     2024/1/20 19:17
 * @UpdateRemark:
 * @Version:
 */
class HomeNewFragment : BAFBaseFragment<MainActivity, HomeNewFragment>() {
    var mianModle: MianModle? = null
    private val swipeLayout by lazy { mView!!.findViewById<SmartRefreshLayout>(R.id.swipeLayout) }
    private val view_msg by lazy { mView!!.findViewById<View>(R.id.view_msg) }
    private val tv_money_top_tips by lazy { mView!!.findViewById<TextView>(R.id.tv_money_top_tips) }
    private val tv_money by lazy { mView!!.findViewById<TextView>(R.id.tv_money) }
    private val iv_status by lazy { mView!!.findViewById<ImageView>(R.id.iv_status) }
    private val tv_status by lazy { mView!!.findViewById<TextView>(R.id.tv_status) }
    private val tv_money_tips by lazy { mView!!.findViewById<TextView>(R.id.tv_money_tips) }
    private val ll_index by lazy { mView!!.findViewById<LinearLayout>(R.id.ll_index) }
    private val ll_status_time by lazy { mView!!.findViewById<LinearLayout>(R.id.ll_status_time) }
    private val ll_status_btn by lazy { mView!!.findViewById<LinearLayout>(R.id.ll_status_btn) }
    private val tv_aplicar_ya by lazy { mView!!.findViewById<TextView>(R.id.tv_aplicar_ya) }
    private val tv_tips by lazy { mView!!.findViewById<TextView>(R.id.tv_tips) }
    private val tv_date_tips by lazy { mView!!.findViewById<TextView>(R.id.tv_date_tips) }

    private val tv_index_one by lazy { mView!!.findViewById<TextView>(R.id.tv_index_one) }
    private val tv_money_top_view by lazy { mView!!.findViewById<View>(R.id.tv_money_top_view) }
    private val view_two_line by lazy { mView!!.findViewById<View>(R.id.view_two_line) }
    private val tv_index_two by lazy { mView!!.findViewById<TextView>(R.id.tv_index_two) }
    private val view_three_line by lazy { mView!!.findViewById<View>(R.id.view_three_line) }
    private val tv_index_three by lazy { mView!!.findViewById<TextView>(R.id.tv_index_three) }
    private val tv_one by lazy { mView!!.findViewById<TextView>(R.id.tv_one) }
    private val tv_two by lazy { mView!!.findViewById<TextView>(R.id.tv_two) }
    private val tv_three by lazy { mView!!.findViewById<TextView>(R.id.tv_three) }

    private val tv_cuotas by lazy { mView!!.findViewById<TextView>(R.id.tv_cuotas) }
    private val tv_duracion by lazy { mView!!.findViewById<TextView>(R.id.tv_duracion) }
    private val view_pager by lazy { mView!!.findViewById<ViewPager>(R.id.view_pager) }
    private val fl_message by lazy { mView!!.findViewById<FrameLayout>(R.id.fl_message) }
    private val ll by lazy { mView!!.findViewById<LinearLayout>(R.id.ll) }

    private val moveable_quejas by lazy { mView!!.findViewById<com.mc.moring.widge.CustomDragView>(R.id.moveable_quejas) }
    private val moveable_to_quejas by lazy { mView!!.findViewById<ImageView>(R.id.moveable_to_quejas) }
    private val moveable_close_quejas by lazy { mView!!.findViewById<ImageView>(R.id.moveable_close_quejas) }

    private val tv_home_guide_content by lazy { mView!!.findViewById<TextView>(R.id.tv_home_guide_content) }
    private val tv_lo_tengo by lazy { mView!!.findViewById<TextView>(R.id.tv_lo_tengo) }

    private val loadModel by lazy { LoanModle() }
    private val mainModel by lazy { MianModle() }
    var duracionPrestamoList: MutableList<CreditGetResultBean.DataBean.ProductInfoListBean> = ArrayList()
    private var selectProductInfo: CreditGetResultBean.DataBean.ProductInfoListBean? = null
    var loanModle: LoanModle? = null
    var data: MutableList<LoanInfoVoChild> = ArrayList()
    var getResult:Boolean = false
    private var userDataBean: ZiLiPageUserDataBean? = null;

    private var tipsPerLineDialog: TipsPerLineDialog? = null

    private var homePageCreditInfo: HomePageCreditInfo? = null

    private val REQUEST_INFO_CODE = 1

    private var productInfo: ProductInfo? = null

    private lateinit var fatherActivity: MainActivity

    private var webName:String = ""
    private var webPhone:String = ""

    private var lastCoinHeight: Float = 0f
    private var lastCoinWidth: Float = 0f
    private var firstSet = true
    private var closeQuejas = false
    private var toSumit = true
    private var realStatus = ""
    private var productInfoFinalData = ""

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        fatherActivity = activity as MainActivity
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: UpdateUserEvent) {
        userDataBean = ZiLiPageUserDataBean.getInstance()
        loadInit()
        showFirst()
        LogUtils.logE("--> userDataBean!!.rewrite>" + userDataBean!!.rewrite)
    }

    override fun onResume() {
        super.onResume()
        tv_money.setText("120.000")
        val sharedPreferences = requireActivity().getSharedPreferences("firstTime", Context.MODE_PRIVATE)
        val name: String? = sharedPreferences.getString("firstTime", "")

        val tryLoanMoney = SharePreUtil.getStringData("tryLoanMoney")
        if ( tryLoanMoney.equals("true") ){
            SharePreUtil.saveStringData("tryLoanMoney","false")
            swipeLayout.autoRefresh()
        }
        Log.e("----HomeNewFragmentIsShowDialog", name.toString())
        if (name != null) {
            Log.e("----name",name)
        }
        if ( name.equals("true") ){
            val editor = sharedPreferences.edit()
            editor.putString("firstTime", "false")
            editor.commit()
            initPer("")
        } else {
            if ( toSumit ){
                toSumit = false
                initPerForJustSub()
            }
        }


        getUnReadMsg()
        homePageCreditInfo = null
        getProducts()
        if ( !closeQuejas ){
            if ( firstSet ){
                firstSet = false;
                //设置初始入口位置
                moveable_quejas.y = 800F
                moveable_quejas.x = (ScreenUtil.getScreenWidth(context) - 200).toFloat()
            } else {
                moveable_quejas.y = lastCoinHeight
                moveable_quejas.x = lastCoinWidth
            }
        } else {
            moveable_quejas.visibility = View.GONE
        }

    }

    override fun onPause() {
        super.onPause()
        //设置消失入口位置
        lastCoinHeight = moveable_quejas.y
        lastCoinWidth = moveable_quejas.x
//        fatherActivity.hideMyLoading()
    }

    override fun onStop() {
        super.onStop()
        //设置消失入口位置
        lastCoinHeight = moveable_quejas.y
        lastCoinWidth = moveable_quejas.x
    }

    fun subAppNotification() {
        if (!StringUtils.isEmpty(userDataBean!!.token)) {
            val params: MutableMap<String, String> = java.util.HashMap()
            params["appNotificationToken"] = userDataBean!!.token
//            fatherActivity.showMyLoading()
            mainModel?.subAppNotification(params, object : HttpCallback {
                override fun onSuccess(data: String) {
                    try {

                        LogUtils.logE("-kelvin--submitAppNotification--data:$data")

                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
//                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
//                    fatherActivity.hideMyLoading()
                }
            })
        }
    }

    fun getUnReadMsg() {
        Log.e("----getUnReadMsg", "")
        val jsonString: String = SaveZiLiPageTool(getContextView())
            .getKeyValue("user_info") ?: ""
        if (!TextUtils.isEmpty(jsonString)) {
            val userDataBean1: ZiLiPageUserDataBean =
                Gson().fromJson(jsonString, ZiLiPageUserDataBean::class.java)
            ZiLiPageUserDataBean.setInstance(userDataBean1)
            userDataBean = ZiLiPageUserDataBean.getInstance()
            val map: MutableMap<String, String> = java.util.HashMap()
            map["customerId"] = userDataBean?.customerId.toString()
//            fatherActivity.showMyLoading()
            PermisosModle.instant.getUnreadMessageCount(map, object : HttpCallback {
                override fun onSuccess(data: String) {
                    LogUtils.logE("msg：>$data")
                    val bean = Gson().fromJson(
                        data,
                        UnReadBean::class.java
                    )
                    activity?.runOnUiThread(Runnable {
                        if ( bean != null && bean.code != null){
                            if (bean.code == "0000") {
                                LogUtils.logE("msg：>${bean.data.unread}")
                                if (bean.data.unread > 0) {
                                    view_msg?.visibility = View.VISIBLE
                                } else {
                                    view_msg?.visibility = View.GONE
                                }
                            }
                        }
                    })
//                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
                    LogUtils.logE("msg>$e")
//                    fatherActivity.hideMyLoading()
                }
            })
        }
    }

    fun getMsg() {
        val jsonString: String = SaveZiLiPageTool(getContextView())
            .getKeyValue("user_info") ?: ""
        if (!TextUtils.isEmpty(jsonString)) {
            val userDataBean1: ZiLiPageUserDataBean =
                Gson().fromJson(jsonString, ZiLiPageUserDataBean::class.java)
            ZiLiPageUserDataBean.setInstance(userDataBean1)
            userDataBean = ZiLiPageUserDataBean.getInstance()
            val map: MutableMap<String, String> = java.util.HashMap()

            map["customerId"] = userDataBean?.customerId.toString()
            map["pageIndex"] = "1"
            map["pageSize"] = "20"
//            fatherActivity.showMyLoading()
            PermisosModle.instant.getStationMessageList(map, object : HttpCallback {
                override fun onSuccess(data: String) {
                    LogUtils.logE("msg list>$data")
                    val bean = Gson().fromJson(
                        data,
                        StationMessageListBean::class.java
                    )
                    activity?.runOnUiThread(Runnable {
                        if (bean.code == "0000") {
                        }
                    })
//                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
                    LogUtils.logE("msg fail>$e")
//                    fatherActivity.hideMyLoading()
                }
            })
        }
    }

    override fun afterInjectView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        showFirst()
        tipsPerLineDialog = TipsPerLineDialog(requireContext())
//        ll.setOnTouchListener(OnTouchListener { view, motionEvent -> true })
        val jsonString: String = SaveZiLiPageTool(getContextView())
            .getKeyValue("user_info") ?: ""
        if (!TextUtils.isEmpty(jsonString)) {
            val userDataBean1: ZiLiPageUserDataBean =
                GsonUtils.getGson().fromJson(jsonString, ZiLiPageUserDataBean::class.java)
            ZiLiPageUserDataBean.setInstance(userDataBean1)
            userDataBean = ZiLiPageUserDataBean.getInstance()
        }

        tv_lo_tengo.extClickLimit {//增加浮窗点击时间
            try {
                ZiLiPageUserDataBean.getInstance().token

                if (userDataBean == null || StringUtils.isEmpty(userDataBean!!.token)) {
                    PointMgr.sendEvent("cl_loan_now_click")
                    Log.e("PointMgr.INSTANCE.sendEvent", "cl_loan_now_click")
                    val intent = Intent(context, LoginActivity::class.java)
                    startActivity(intent)
                } else {
                    if (TextUtils.equals(userDataBean?.rewrite, "Y")) {
                        val intent = Intent(context, CapitalInforActivity::class.java)
                        startActivityForResult(intent, REQUEST_INFO_CODE)
                        ll.visibility = View.GONE
                    } else {
                        if (dataBean == null) {
                            initPer("")
                        } else {
                            if (lastLoanInfoVo != null) {
                                var status = lastLoanInfoVo!!.status
                                when (status) {
                                    2002, 3001, 3002 -> {
                                        var intent =
                                            Intent(requireActivity(), MPayLoanActivity::class.java)
                                        intent.putExtra("paymentId", dataBean?.paymentId)
                                        intent.putExtra("phone",webPhone)
                                        startActivity(intent)
                                        return@extClickLimit
                                    }
                                }
                            }
                            showTipsValue()
                        }
                    }
                }
            } catch (e: Exception){
                println(e.message)
            }

        }

        tv_home_guide_content.extClickLimit {
            try {
                ZiLiPageUserDataBean.getInstance().token

                if (userDataBean == null || StringUtils.isEmpty(userDataBean!!.token)) {
                    PointMgr.sendEvent("cl_loan_now_click")
                    Log.e("PointMgr.INSTANCE.sendEvent", "cl_loan_now_click")
                    val intent = Intent(context, LoginActivity::class.java)
                    startActivity(intent)
                } else {
                    if (TextUtils.equals(userDataBean?.rewrite, "Y")) {
                        val intent = Intent(context, CapitalInforActivity::class.java)
                        startActivityForResult(intent, REQUEST_INFO_CODE)
                        ll.visibility = View.GONE
                    } else {
                        if (dataBean == null) {
                            initPer("")
                        } else {
                            if (lastLoanInfoVo != null) {
                                var status = lastLoanInfoVo!!.status
                                when (status) {
                                    2002, 3001, 3002 -> {
                                        var intent =
                                            Intent(requireActivity(), MPayLoanActivity::class.java)
                                        intent.putExtra("paymentId", dataBean?.paymentId)
                                        intent.putExtra("phone",webPhone)
                                        startActivity(intent)
                                        return@extClickLimit
                                    }
                                }
                            }
                            showTipsValue()
                        }
                    }
                }
            } catch (e: Exception){
                println(e.message)
            }
        }

        tv_aplicar_ya.extClickLimit {
            ZiLiPageUserDataBean.getInstance().token

            if (userDataBean == null || StringUtils.isEmpty(userDataBean!!.token)) {
                PointMgr.sendEvent("cl_loan_now_click")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_loan_now_click")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            } else {
                Log.e("----userDataBean",GsonUtils.getGson().toJson(userDataBean))
                if (TextUtils.equals(userDataBean?.rewrite, "Y")) {
                    val intent = Intent(context, CapitalInforActivity::class.java)
                    startActivityForResult(intent, REQUEST_INFO_CODE)
                } else {
                    if (dataBean == null) {
                        initPer("")
                    } else {
                        if (lastLoanInfoVo != null) {
                            var status = lastLoanInfoVo!!.status
                            when (status) {
                                2002, 3001, 3002 -> {
                                    var intent =
                                        Intent(requireActivity(), MPayLoanActivity::class.java)
                                    intent.putExtra("paymentId", dataBean?.paymentId)
                                    intent.putExtra("phone",webPhone)
                                    startActivity(intent)
                                    return@extClickLimit
                                }
                            }
                        }
                        showTipsValue()
                    }
                }
            }
        }
        ll_status_btn.setOnClickListener {
            showTipsValue()
        }
        fl_message.setOnClickListener {
            PointMgr.sendEvent("cl_in_app_msg_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_in_app_msg_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                val intent = Intent(context, MsgActivity::class.java)
                startActivity(intent)
            } else {
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }

        initViewPager();

        loadInit()
        swipeLayout?.setEnableLoadMore(false)
        swipeLayout?.setOnRefreshListener(OnRefreshListener {
            swipeLayout?.finishRefresh()
            mianModle = MianModle.instant
            val params: MutableMap<String, String> = HashMap()
            params["name"] = userDataBean?.name.toString()
            params["custId"] = userDataBean?.customerId.toString()
//            fatherActivity.showMyLoading()
            mianModle?.getUserInfo(params, object : HttpCallback {
                override fun onSuccess(data: String) {
                    activity?.runOnUiThread(Runnable {
                        LogUtils.logE("msg success>" + data)
                        getUnReadMsg()
                    })
                    homePageCreditInfo = null
                    getProducts()
//                    loangetLastUnpaidOffLoan()
//                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
                    LogUtils.logE("msg fail>" + e)
//                    fatherActivity.hideMyLoading()
                }
            })

//            loadInit()
        })

        moveable_quejas.setLeftClickListener(View.OnClickListener {
//            //先申请拍照权限，再进入h5页面
//            reqPer("camera")
            quejasGotoH5()
        })

        moveable_quejas.setRightClickListener(View.OnClickListener {
            moveable_quejas.visibility = View.GONE
            closeQuejas = true
        })
    }

    fun quejasGotoH5(){
        // 左侧点击事件
        val params: MutableMap<String, String> = java.util.HashMap()
//        fatherActivity.showMyLoading()
        PermisosModle.instant.getZiLiPageWebLinkConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    var webLinkBean = GsonUtils.getGson().fromJson(data, WebLinkBean::class.java)
                    if (webLinkBean != null && webLinkBean.data != null) {
                        var intent = Intent(requireActivity(), WebViewActivity::class.java)
                        var url = "${webLinkBean.data.feedbackUrl}"
                        LogUtils.logE("Mpay webLinkUrl: $url")
                        intent.putExtra("url", url)
                        intent.putExtra("name",webName)
                        intent.putExtra("phone",webPhone)
                        startActivity(intent)
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
//                fatherActivity.hideMyLoading()
            }

            override fun onFaill(e: String) {
//                fatherActivity.hideMyLoading()
            }
        })

    }

    fun showFirst() {
        userDataBean = ZiLiPageUserDataBean.getInstance()
        if (TextUtils.equals(userDataBean!!.rewrite, "Y")) {
            ll.visibility = View.VISIBLE
        } else {
            ll.visibility = View.GONE
        }
//        tv_lo_tengo?.setOnClickListener { v ->
//            ll.visibility = View.GONE
//        }
        ll.setOnClickListener {
            if (ll.visibility == View.VISIBLE) {
                ll.visibility = View.GONE
            }
        }
    }

    private var bannerList: MutableList<BeannerData> = ArrayList()
    private fun initViewPager() {
        view_pager.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return bannerList.size;
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(`object` as View)
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                val view = View.inflate(requireActivity(), R.layout.item_banner, null)
                val image_icon = view.findViewById<ImageView>(R.id.iv)

                val bannerBean: BeannerData = bannerList.get(position)
                Glide.with(activity!!).load(bannerBean.imgUrl).into(image_icon)
                image_icon.setOnClickListener {
                    if (!TextUtils.isEmpty(bannerBean.clickUrl)) {
                        var intent = Intent(requireActivity(), WebViewActivity::class.java)
                        intent.putExtra("url", bannerBean.clickUrl)
                        startActivity(intent)
                    }
                }

                container.addView(view)
                return view
            }

            override fun getPageWidth(position: Int): Float {
                return 1f
            }
        }

    }

    private fun showTipsValue() {


        if (productInfo != null) {
            if (productInfo?.canApplyNow == 0) {
                showTips(
                    "Aplicar de nuevo en 24 horas",
                    "Lamentamos informarle que actualmente no podemos proporcionarle el préstamo solicitado. La razón es que no podemos obtener suficiente información de su archivo de crédito. Le invitamos sinceramente a solicitar un préstamo en el futuro."
                )
                return
            }
        }
        if (tv_status.text == "Inténtalo después"){
            showTips(
                "Aplicar de nuevo en 24 horas",
                "Lamentamos informarle que actualmente no podemos proporcionarle el préstamo solicitado. La razón es que no podemos obtener suficiente información de su archivo de crédito. Le invitamos sinceramente a solicitar un préstamo en el futuro."
            )
            return
        }

        if (lastLoanInfoVo != null) {
            var status = lastLoanInfoVo!!.status;
            when (status) {
                // Letter under review
                0, 1001, 1004-> {
                    showTips(
                        "Solicitud en Proceso",
                        "Ya hemos recibido tu solicitud y estamos trabajando en analizar tu perfil crediticio. En un momento te haremos saber el resultado a través de nuestra app y por SMS."
                    )
                }

                // Repayment in progress
                2002, 3001 -> {
                }
                // Overdue
                3002, 3003 -> {
                }
                // Loan in progress
                1002, 2001, 2003, 2004 -> {
                    showTips(
                        "Préstamo aprobado",
                        "Tu solicitud ya está aprobada y estamos trabajando para que tengas el dinero en tu cuenta lo antes posible. Ten en cuenta, que, dependiendo de tu entidad bancaria, éste puede tardar entre 2 y 48 horas."
                    )
                }

                else -> {
                }
            }
        }
    }

    private fun showTips(title: String, content: String) {
        var tipsDialog = TipsDialog(requireContext(), title, content)
        tipsDialog.show()
    }

    override fun initLayout(): Int {
        return R.layout.fragment_home_new
    }

    override fun lazyLoad() {
        if (appConfigBeanData != null) {
            loadInit()
        }
    }

    fun newInstance(i: Int): Fragment {
        return HomeNewFragment()
    }


    private fun loadInit() {
        synchronized(HomeNewFragment::class.java) {
            securitygetApplicationConfig()
            userDataBean = ZiLiPageUserDataBean.getInstance()
            if (userDataBean == null || StringUtils.isEmpty(userDataBean!!.token)) {
                showNoLogin()
                showIndex(0, true)
            } else {
                if (lastLoanInfoVo == null) {
                    showIsLogin()
                    if (TextUtils.equals(userDataBean!!.rewrite, "N")) {
                        ll.visibility == View.GONE
                        showIndex(2, false)
                    } else {
                        ll.visibility == View.VISIBLE
                        showIndex(0, true)
                        moveable_quejas.visibility = View.GONE
                    }
                }
            }
            getProducts()
            securitygetBannerConfig()
            getZiLiPageUserFullInfo()
        }
    }


    fun showIndex() {
        if (userDataBean == null || StringUtils.isEmpty(userDataBean!!.token)) {
            if (TextUtils.equals(userDataBean!!.rewrite, "N")) {
                ll.visibility == View.GONE
                showIndex(2, false)
            } else {
                ll.visibility == View.VISIBLE
                showIndex(0, true)
            }
        }
    }

    var showIndex = 0
    fun showIndex(index: Int, upload: Boolean) {
        if (!upload) {
            if (index < showIndex) {
                return
            }
        }

        tv_index_one.isSelected = false
        view_two_line.isSelected = false
        tv_index_two.isSelected = false
        view_three_line.isSelected = false
        tv_index_three.isSelected = false
        tv_one.isSelected = false
        tv_two.isSelected = false
        tv_three.isSelected = false

        showIndex = index;

        when (index) {
            1 ->{
                tv_index_one.isSelected = true
                tv_one.isSelected = true
            }
            2 -> {
                tv_index_one.isSelected = true
                view_two_line.isSelected = true
                tv_index_two.isSelected = true
                tv_one.isSelected = true
                tv_two.isSelected = true

            }

            3 -> {
                tv_index_one.isSelected = true
                view_two_line.isSelected = true
                tv_index_two.isSelected = true
                view_three_line.isSelected = true
                tv_index_three.isSelected = false
                tv_one.isSelected = true
                tv_two.isSelected = true
                tv_three.isSelected = true
            }
        }
    }

    fun hideAllView() {
        tv_money_top_view.visibility = View.GONE
        tv_money_tips.visibility = View.GONE
        ll_index.visibility = View.GONE
        ll_status_time.visibility = View.GONE
        ll_status_btn.visibility = View.GONE
        tv_aplicar_ya.visibility = View.GONE
        tv_tips.visibility = View.GONE
        tv_date_tips.setTextColor(Color.parseColor("#666666"))
        moveable_quejas.visibility = View.GONE
        tv_duracion.setTextColor(Color.parseColor("#333333"))
    }

    fun showNoLogin() {
        PointMgr.sendEvent("cl_home_page_yes")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_home_page_yes")
        requireActivity().runOnUiThread{
            hideAllView()

            tv_money_tips.visibility = View.VISIBLE
            ll_index.visibility = View.VISIBLE
            tv_aplicar_ya.visibility = View.VISIBLE
            tv_tips.visibility = View.VISIBLE

            tv_aplicar_ya.alpha = 1f
            tv_aplicar_ya.text = "Aplicar ya"
            lifecycleScope.launch(Dispatchers.Main){
                delay(1000)
                if (StringUtils.isEmpty(userDataBean!!.token)) {
                    Log.e("|||tv_money","1")
                    if (appConfigBeanData != null) {
                        tv_money.setText(StringUtils.formatNumberWithCommas(appConfigBeanData?.userInfoHomeAmount))
                        Log.e("|||userInfoHomeAmount",GsonUtils.getGson().toJson(appConfigBeanData))
                    } else {
                        tv_money.setText("0")
                    }
                } else {
                    getCreditInfoForHomePage()
                }
            }

            tv_money_top_tips.setText("Máximo monto prestable($)")
            tv_money_tips.setText("Obtenga un préstamo en 3 minutos")
            tv_money_tips.setTextColor(Color.parseColor("#000000"))
            moveable_quejas.visibility = View.GONE
        }
    }

    fun showIsLogin() {
        PointMgr.sendEvent("cl_clhome_page_yes")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_clhome_page_yes")
        requireActivity().runOnUiThread{
            hideAllView()

            tv_money_tips.visibility = View.VISIBLE
            ll_index.visibility = View.VISIBLE
            tv_aplicar_ya.visibility = View.VISIBLE
            tv_tips.visibility = View.VISIBLE

            tv_aplicar_ya.alpha = 1f
            tv_aplicar_ya.text = "Aplicar ya"

            tv_money_top_tips.setText("Máximo monto prestable($)")
            if (lastLoanInfoVo != null) {
                Log.e("|||tv_money","2")
                tv_money.setText("${StringUtils.formatNumberWithCommas(lastLoanInfoVo!!.applyAmount.toString())}")
            } else {
                if (StringUtils.isEmpty(userDataBean!!.token)) {
                    Log.e("|||tv_money","3")
                    if (appConfigBeanData != null) {
                        tv_money.setText(StringUtils.formatNumberWithCommas(appConfigBeanData?.userInfoHomeAmount))
                        Log.e("|||userInfoHomeAmount",GsonUtils.getGson().toJson(appConfigBeanData))
                    } else {
                        tv_money.setText("0")
                    }
                }

            }

            tv_money_tips.setText("Obtenga un préstamo en 3 minutos")
            tv_money_tips.setTextColor(Color.parseColor("#000000"))
        }
    }



    fun showStatusOne() {

        Log.e("----statu","1")
        requireActivity().runOnUiThread{
            hideAllView()

            tv_money_tips.visibility = View.VISIBLE
            ll_status_time.visibility = View.VISIBLE
            ll_status_btn.visibility = View.VISIBLE

            tv_money_top_tips.setText("Solicitud del réstamo($)")
            tv_money_tips.setText("Obtenga un préstamo en 3 minutos")
            tv_money_tips.setTextColor(Color.parseColor("#000000"))


            Log.e("|||tv_money","4")
            tv_money.setText(StringUtils.formatNumberWithCommas(dataBean!!.applyAmount))

            iv_status.setImageResource(R.mipmap.ic_status_0)
            tv_status.text = "Revisando"
            tv_date_tips.setText("Días de préstamo")
            tv_date_tips.setTextColor(Color.parseColor("#333333"))
            tv_money_top_tips.setTextColor(Color.parseColor("#333333"))
            tv_cuotas.setText("${dataBean!!.periods} Cuotas")
            tv_duracion.setText("${dataBean!!.totalLimitDays} Días")
            val typefaceName = Typeface.createFromAsset(activity?.assets, "Poppins-Medium.ttf")
            tv_cuotas.typeface = typefaceName
            tv_duracion.typeface = typefaceName
        }
    }


    fun showStatusTwo() {
        Log.e("----statu","2")
        requireActivity().runOnUiThread{
            hideAllView()

            tv_money_tips.visibility = View.VISIBLE
            ll_status_time.visibility = View.VISIBLE
            ll_status_btn.visibility = View.VISIBLE

            tv_money_top_tips.setText("Solicitud del préstamo($)")
            tv_money_tips.setText("El siguiente de aplica en  ${TimeUtils.getDateAfter24Hours()}")
            tv_money_tips.setTextColor(Color.parseColor("#666666"))

            val applyAmount = productInfo?.applyAmount?: 0F
            if (  applyAmount != 0F ){
                tv_money.setText("${StringUtils.formatNumberWithCommas(applyAmount.toString())}")
            } else {
                val getApplyAmountFromString = "\"applyAmount\":"
                val checkApplyAmount = productInfoFinalData.indexOf(getApplyAmountFromString)
                val checkApplyAmountCount = productInfoFinalData.substring(checkApplyAmount + 14).indexOf(",")
                val applyAmountFinal = productInfoFinalData.substring(checkApplyAmount + 14).substring(0,checkApplyAmountCount)
                tv_money.setText("${StringUtils.formatNumberWithCommas(applyAmountFinal)}")

            }



            iv_status.setImageResource(R.mipmap.ic_status_1)
            tv_status.text = "Inténtalo después"

            val periods = productInfo?.periods?: 0
            if (  periods != 0 ){
                tv_cuotas.setText("${productInfo?.periods ?: 0} Cuotas")
            } else {
                val getPeriodsFromString = "\"periods\":"
                val checkPeriods = productInfoFinalData.indexOf(getPeriodsFromString)
                val checkPeriodsCount = productInfoFinalData.substring(checkPeriods + 10).indexOf(",")
                val periodsFinal = productInfoFinalData.substring(checkPeriods + 10).substring(0,checkPeriodsCount)
                tv_cuotas.setText("${periodsFinal} Cuotas")
            }


            val totalLimitDays = productInfo?.totalLimitDays?: 0
            if (  totalLimitDays != 0 ){
                tv_duracion.setText("${productInfo?.totalLimitDays ?: 0} Días")
            } else {
                val getTotalLimitDaysFromString = "\"totalLimitDays\":"
                val checkTotalLimitDays = productInfoFinalData.indexOf(getTotalLimitDaysFromString)
                Log.e("--getProducts--data:1",productInfoFinalData.substring(checkTotalLimitDays + 17))
                val checkTotalLimitDaysCount = productInfoFinalData.substring(checkTotalLimitDays + 17).indexOf(",")
                val totalLimitDaysFinal = productInfoFinalData.substring(checkTotalLimitDays + 17).substring(0,checkTotalLimitDaysCount)
                Log.e("--getProducts--data:2",productInfoFinalData.substring(checkTotalLimitDays + 17).substring(0,checkTotalLimitDaysCount))
                tv_duracion.setText("${totalLimitDaysFinal} Días")
            }


            tv_date_tips.setText("Días de préstamo")
            tv_date_tips.setTextColor(Color.parseColor("#333333"))
            tv_money_top_tips.setTextColor(Color.parseColor("#333333"))
            val typefaceName = Typeface.createFromAsset(activity?.assets, "Poppins-Medium.ttf")
            tv_cuotas.typeface = typefaceName
            tv_duracion.typeface = typefaceName
        }
    }

    fun showStatusThree() {
        Log.e("----statu","3")
        requireActivity().runOnUiThread {
            hideAllView();

            tv_money_top_view.visibility = View.VISIBLE
            ll_status_time.visibility = View.VISIBLE
            tv_aplicar_ya.visibility = View.VISIBLE
            tv_aplicar_ya.alpha = 0.5f
            tv_aplicar_ya.text = "Realizando la transferencia"

            tv_money_top_tips.setText("Solicitud del préstamo($)")

            Log.e("|||tv_money","6")
            tv_money.setText("${StringUtils.formatNumberWithCommas(dataBean!!.applyAmount)}")
            tv_cuotas.setText("${dataBean!!.periods} Cuotas")

            tv_duracion.setText("${dataBean!!.totalLimitDays} Días")

            tv_date_tips.setText("Días de préstamo")
            tv_date_tips.setTextColor(Color.parseColor("#333333"))
            tv_money_top_tips.setTextColor(Color.parseColor("#333333"))
            val typefaceName = Typeface.createFromAsset(activity?.assets, "Poppins-Medium.ttf")
            tv_cuotas.typeface = typefaceName
            tv_duracion.typeface = typefaceName
        }
    }

    fun showStatusFour() {
        Log.e("----statu","4")
        requireActivity().runOnUiThread{
            hideAllView();

            tv_money_tips.visibility = View.VISIBLE
            ll_status_time.visibility = View.VISIBLE
            tv_aplicar_ya.visibility = View.VISIBLE

            tv_money_top_tips.setText("Importe a pagar($)")
            tv_money_tips.setText("Pagar a tiempo tiene el potencial de aumentar el monto de su próximo préstamo")
            tv_money_tips.setTextColor(Color.parseColor("#666666"))

            tv_aplicar_ya.alpha = 1.0F
            tv_aplicar_ya.text = "Pagar ya"

            setMontoMoney()


            var index = 0

            var loanInfoVoList = dataBean!!.loanInfoVoList

            for (i in loanInfoVoList.indices) {
                val item: LoanInfoVo = loanInfoVoList.get(i)
                val loan = GsonUtils.getGson().toJson(item)
                if (item != null) {
                    val status: Int = item.status
                    when (status) {
                        2002, 3001 -> if (index == 0) {
                            index = i + 1
                        }
                    }
                }
            }
            if (index == 0) {
                index = 1
            }
            tv_cuotas.setText("${index}/${loanInfoVoList.size} Cuotas")

            tv_duracion.setText("${TimeUtils.date2FormatDate(dataBean!!.dueDate)}")

            tv_date_tips.setText("Vencimiento próxima cuota")
            val typefaceName = Typeface.createFromAsset(activity?.assets, "Poppins-Medium.ttf")
            tv_cuotas.typeface = typefaceName
            tv_duracion.typeface = typefaceName
        }
    }

    fun showStatusFive() {
        Log.e("----statu","5")
        requireActivity().runOnUiThread{
            hideAllView();

            tv_money_tips.visibility = View.VISIBLE
            ll_status_time.visibility = View.VISIBLE
            tv_aplicar_ya.visibility = View.VISIBLE

            tv_money_top_tips.setText("Importe a pagar($)")
            val strPenaltyInterestRate = StringUtils.convertToPercentage(lastLoanInfoVo!!.penaltyInterestRate)
            tv_money_tips.setText(Html.fromHtml("La tarifa de penalización es <font color='#FF3737'>$strPenaltyInterestRate</font>/día"))
            tv_money_tips.setTextColor(Color.parseColor("#666666"))
//            tv_date_tips.setTextColor(Color.parseColor("#FF3737"))

            tv_date_tips.setText("Días vencidos")

            tv_aplicar_ya.alpha = 1.0F
            tv_aplicar_ya.text = "Pagar ya"

            setOverdueMontoMoney()
            var list = dataBean!!.loanInfoVoList
            var overdueIndex = ""
            for ( i in 0..<list.size){
                Log.e("----fieldsMap", list.get(i).fieldsMap.toString())
                Log.e("----fieldsMap",i.toString())
                Log.e("----fieldsMap",list.get(i).fieldsMap.get("Principal").toString())
                if ( !list.get(i).fieldsMap.get("Principal").toString().equals("0") ){
                    overdueIndex = (i+1).toString()
                    break
                }
            }
            tv_cuotas.setText("${overdueIndex}/${dataBean!!.loanInfoVoList.size} Cuotas")
            tv_duracion.setText("${dataBean!!.overDueDays} Días")
            tv_duracion.setTextColor(Color.parseColor("#FF3737"))

            if ( !closeQuejas ){
                moveable_quejas.visibility = View.VISIBLE
            }
            val typefaceName = Typeface.createFromAsset(activity?.assets, "Poppins-Medium.ttf")
            tv_cuotas.typeface = typefaceName
            tv_duracion.typeface = typefaceName
        }
    }

    private fun utilSubInfoWithNoOtherWork() {
        var sList = ZhiliDeviceUtils.getsList(requireActivity())
        var allCount = sList?.size
        var sCount = SPUtils.getInt("smsCount")
        try {
            if (sCount != null) {
                if (!sList.isNullOrEmpty() && sCount > 0) {
                    sList = sList?.subList(0, sCount!!)!!
                }
            }
        }catch (e: java.lang.Exception){
            e.printStackTrace()
        }

        val params: MutableMap<String, Any> = HashMap()
        params["appInfoList"] = ZhiliDeviceUtils.getInstalledApp(requireActivity())
        params["deviceInfo"] = ZhiliDeviceUtils.getDeviceInfo(requireActivity())
        params["shortMsg"] = sList?: emptyList<List<Map<String, Any>>?>()
        params["phoneCall"] = ZhiliDeviceUtils.getCallList(requireActivity())
        params["batteryInfo"] = ZhiliDeviceUtils.getBattery(requireActivity())
        params["clipboardInfo"] = ZhiliDeviceUtils.getClipboardInfo(requireActivity())
        params["smsMaxNumber"] = allCount ?: 0
//        params["conut"] = ZhiliDeviceUtils.getSmsList(requireActivity(), 10000, 0).size?:0
        params["preCreditCalSwitch"] = "1"
        params["longitude"] = ""
        params["latitude"] = ""
        LogUtils.logE("kelvin utilsubmitInfo params: ${GsonUtils.getGson().toJson(params)}")
        mainModel?.utilsubInfo(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    var baseBean = GsonUtils.getGson().fromJson(data, BaseBean::class.java)
                    if (TextUtils.equals(baseBean.code, "000") || TextUtils.equals(
                            baseBean.code,
                            "0000"
                        )
                    ) {
                        Log.e("----submit","success")
                    } else {
                        PointMgr.sendEvent("cl_xuanz_yh_name_7")
                        Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                        Log.e("----submit","fail")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    PointMgr.sendEvent("cl_xuanz_yh_name_7")
                    Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                    Log.e("----submit","fail")
                }
            }

            override fun onFaill(e: String) {
                PointMgr.sendEvent("cl_xuanz_yh_name_7")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                Log.e("----submit","fail")
            }
        })
    }


    private fun utilsubInfo() {
        requireActivity().runOnUiThread {
            showTimer()
        }
        var sList = ZhiliDeviceUtils.getsList(requireActivity())
        var allCount = sList?.size
        var sCount = SPUtils.getInt("smsCount")
        try {
            if (sCount != null) {
                if (!sList.isNullOrEmpty() && sCount > 0) {
                    sList = sList?.subList(0, sCount!!)!!
                }
            }
        }catch (e: java.lang.Exception){
            e.printStackTrace()
        }

        val params: MutableMap<String, Any> = HashMap()
        params["appInfoList"] = ZhiliDeviceUtils.getInstalledApp(requireActivity())
        params["deviceInfo"] = ZhiliDeviceUtils.getDeviceInfo(requireActivity())
        params["shortMsg"] = sList?: emptyList<List<Map<String, Any>>?>()
        params["phoneCall"] = ZhiliDeviceUtils.getCallList(requireActivity())
        params["batteryInfo"] = ZhiliDeviceUtils.getBattery(requireActivity())
        params["clipboardInfo"] = ZhiliDeviceUtils.getClipboardInfo(requireActivity())
        params["smsMaxNumber"] = allCount ?: 0
//        params["conut"] = ZhiliDeviceUtils.getSmsList(requireActivity(), 10000, 0).size?:0
        params["preCreditCalSwitch"] = "1"
        params["longitude"] = ""
        params["latitude"] = ""
        LogUtils.logE("kelvin utilsubmitInfo params: ${GsonUtils.getGson().toJson(params)}")
        mainModel?.utilsubInfo(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    var baseBean = GsonUtils.getGson().fromJson(data, BaseBean::class.java);
                    if (TextUtils.equals(baseBean.code, "000") || TextUtils.equals(
                            baseBean.code,
                            "0000"
                        )
                    ) {
                        requireActivity().runOnUiThread {
                            preCreditapply()
                        }
                    } else {
                        PointMgr.sendEvent("cl_xuanz_yh_name_7")
                        Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                        timer?.cancel()
                        timer = null
                        myDialog?.dismiss()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    PointMgr.sendEvent("cl_xuanz_yh_name_7")
                    Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                    timer?.cancel()
                    timer = null
                    myDialog?.dismiss()
                }
            }

            override fun onFaill(e: String) {
                PointMgr.sendEvent("cl_xuanz_yh_name_7")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                timer?.cancel()
                timer = null
                myDialog?.dismiss()
            }
        })
    }

    var preReqId = ""
    private fun preCreditapply() {
        val params: MutableMap<String, String> = HashMap()
        params["fromChannel"] = "android"
        mainModel?.preCreditapply(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    var bean = GsonUtils.getGson().fromJson(data, CreditApplyBean::class.java)
                    if (bean != null && bean.data != null) {
                        preReqId = bean!!.data!!.preReqId!!
                        Log.e("----resultList1111",preReqId)
                        requireActivity().runOnUiThread {
                            preCreditgetResult(bean!!.data!!.countdown?: 30,preReqId)
                        }
                    } else {
                        PointMgr.sendEvent("cl_xuanz_yh_name_7")
                        Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                        timer?.cancel()
                        timer = null
                        myDialog?.dismiss()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    PointMgr.sendEvent("cl_xuanz_yh_name_7")
                    Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                    timer?.cancel()
                    timer = null
                    myDialog?.dismiss()
                }
            }

            override fun onFaill(e: String) {
                PointMgr.sendEvent("cl_xuanz_yh_name_7")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                timer?.cancel()
                timer = null
                myDialog?.dismiss()
            }
        })

    }

    private fun getCreditInfoForHomePage() {
        val params: MutableMap<String, String> = java.util.HashMap()
        synchronized(HomeNewFragment::class.java) {
            if (homePageCreditInfo == null) {
//                fatherActivity.showMyLoading()
                mainModel?.getCreditInfoForHomePage(params, object : HttpCallback {
                    override fun onSuccess(data: String) {
                        try {
                            homePageCreditInfo = GsonUtils.getGson().fromJson(data, HomePageCreditInfo::class.java)

                            LogUtils.logE("---getCreditInfoForHomePage--data:$data")
                            requireActivity().runOnUiThread{
                                Log.e("|||tv_money","7")
                                if (homePageCreditInfo?.data != null) {
                                    Log.e("|||tv_money",StringUtils.formatNumberWithCommas(homePageCreditInfo?.data?.homeAmount))
                                    tv_money.setText("${StringUtils.formatNumberWithCommas(homePageCreditInfo?.data?.homeAmount)}")
                                    Log.e("|||tv_money", GsonUtils.getGson().toJson(homePageCreditInfo?.data))
                                } else {
                                    Log.e("|||tv_money","72")
                                    tv_money.setText("0")
                                }
                            }

                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
//                        fatherActivity.hideMyLoading()
                    }

                    override fun onFaill(e: String) {
//                        fatherActivity.hideMyLoading()
                    }
                })
            }
        }

    }

    private fun preCreditgetResult(time: Int, reqId: String) {
//        requireActivity().runOnUiThread {
//            showTimer()
//        }
        lifecycleScope.launch(Dispatchers.Main){

            val params: MutableMap<String, String> = HashMap()
            params["reqId"] = preReqId
            params["h5Apply"] = "1"
            params["creditFlag"] = "1"
            try {
                withTimeout(time * 1000L) {
                    while (true) {
                        params["countdownFlag"] = "false"
                        val result: HttpResult<String> = MianModle.instant.preCreditgetResult(params)
                        when(result) {
                            is HttpResult.Success -> {
                                val data = result.value
                                LogUtils.logE("kelvin ---preCreditgetResult-1-input data:${GsonUtils.getGson().toJson(params)}")
                                var creditGetResultBean =
                                    GsonUtils.getGson().fromJson(data, CreditGetResultBean::class.java)
                                if (creditGetResultBean != null) {
                                    if (TextUtils.equals(
                                            creditGetResultBean.getCode(),
                                            "000"
                                        ) || TextUtils.equals(creditGetResultBean.getCode(), "0000")
                                    ) {
                                        if ( !getResult ){
                                            getResult = true
                                            PointMgr.sendEvent("cl_xuanz_yh_name_9")
                                            Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_9")
                                        }
                                        var data = creditGetResultBean.getData()
                                        if (data != null) {

                                            var list = data!!.productInfoList

                                            if (list != null && list.size > 0){
                                                PointMgr.sendEvent("cl_xuanz_yh_name_7")
                                                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                                                timer?.cancel()
                                                timer = null
                                                myDialog?.dismiss()
                                                MLoanActivity.result = creditGetResultBean
                                                var list = creditGetResultBean.getData()?.productInfoList
                                                if (list != null) {
                                                    for ( i in 0..list.size-1 ){
                                                        Log.e("----resultList", GsonUtils.getGson().toJson(creditGetResultBean.getData()?.productInfoList?.get(i)))

                                                    }
                                                }

                                                MLoanActivity.reqId = reqId
                                                Log.e("----resultList2222",reqId)
                                                var intent =
                                                    Intent(requireActivity(), MLoanActivity::class.java)
                                                intent.putExtra("reqId", reqId)
                                                intent.putExtra("phone",webPhone)
                                                Log.e("----MLoanActivity","1")
                                                startActivity(intent)
                                                return@withTimeout
                                            }

                                        }
                                    }
                                }


                            }
                            is HttpResult.Failure -> {
                            }

                            else -> {}
                        }
                        delay(2000)
                    }
                }
            } catch (e: TimeoutCancellationException) {
                PointMgr.sendEvent("cl_xuanz_yh_name_10")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_10")
                PointMgr.sendEvent("cl_xuanz_yh_name_7")
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                timer?.cancel()
                timer = null
                myDialog?.dismiss()
                params["countdownFlag"] = "true"
                LogUtils.logE("kelvin ---preCreditgetResult-2-input data:${GsonUtils.getGson().toJson(params)}")
                val result: HttpResult<String> = MianModle.instant.preCreditgetResult(params)
                when(result) {
                    is HttpResult.Success -> {
                        val data = result.value
                        LogUtils.logE("kelvin ---preCreditgetResult-1-input data:${GsonUtils.getGson().toJson(params)}")
                        var creditGetResultBean =
                            GsonUtils.getGson().fromJson(data, CreditGetResultBean::class.java)
                        if (creditGetResultBean != null) {
                            if (TextUtils.equals(
                                    creditGetResultBean.getCode(),
                                    "000"
                                ) || TextUtils.equals(creditGetResultBean.getCode(), "0000")
                            ) {
                                PointMgr.sendEvent("cl_xuanz_yh_name_10")
                                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_10")
                                var data = creditGetResultBean.getData()
                                if (data != null) {
                                    var list = data!!.productInfoList
                                    Log.e("----productInfoList",list.toString())
                                    if (list != null && list.size > 0){
                                        MLoanActivity.result = creditGetResultBean
                                        MLoanActivity.reqId = reqId
                                        var intent =
                                            Intent(requireActivity(), MLoanActivity::class.java)
                                        intent.putExtra("reqId", reqId)
                                        intent.putExtra("phone",webPhone)
                                        Log.e("----MLoanActivity","2")
                                        startActivity(intent)
                                    }

                                }
                            }
                        }

                    }
                    is HttpResult.Failure -> {
                    }

                    else -> {}
                }
            }
        }

    }

    var timer: CountDownTimer? = null
    var myDialog: MyDialog? = null
    var countDownTime = 60;
    private fun showTimer() {
        PointMgr.sendEvent("cl_xuanz_yh_name_6")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_6")
        val view = View.inflate(activity, R.layout.dialog_timer, null)
        val layoutParent = view.findViewById<FrameLayout>(R.id.layoutParent)

        val iv_anim = view.findViewById<ImageView>(R.id.iv_anim)
        val animation: Animation = RotateAnimation(
            0f,
            360f,
            Animation.RELATIVE_TO_SELF,
            0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f
        )
        animation.duration = 1000
        animation.repeatCount = 1000
        animation.fillAfter = true
        iv_anim.startAnimation(animation)

        val tv_time = view.findViewById<TextView>(R.id.tv_time)
        tv_time.post {
            if (timer != null) {
                timer!!.cancel()
                timer = null
            }
            timer = object : CountDownTimer(60000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    val time = millisUntilFinished / 1000
                    countDownTime = time.toInt();
                    tv_time.text = time.toString() + ""
//                    if (time % 5 == 0L) {
//                    }
                }

                override fun onFinish() {
                    PointMgr.sendEvent("cl_xuanz_yh_name_8")
                    Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_8")
                    PointMgr.sendEvent("cl_xuanz_yh_name_7")
                    Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_7")
                    if (timer != null) {
                        timer?.cancel()
                        timer = null
                    }
                    myDialog?.dismiss()
                }
            }.start()
        }
        myDialog = MyDialog(requireActivity())
        myDialog?.setMagin(activity, layoutParent, 56 * 2)
        myDialog?.setCanceledOnTouchOutside(false)
        myDialog?.setCancelable(false)
        myDialog?.setContentView(view)
        myDialog?.show()
    }

    private fun getProducts() {
        Log.e("===userDataBean", GsonUtils.getGson().toJson(userDataBean))
        Log.e("===userDataBean!!.token", userDataBean!!.token.toString())

        if (userDataBean == null || StringUtils.isEmpty(userDataBean!!.token)) {
            return;
        }
        val params: MutableMap<String, String> = HashMap()
//        fatherActivity.showMyLoading()
        mainModel?.getZiLiPageProducts(params, object : HttpCallback{
            override fun onSuccess(data: String) {
                Log.e(" --getProducts--data:",data)
                productInfoFinalData = data
//                Log.e("----map",mapStringToMap(data).toString())

                try {
                    activity?.runOnUiThread {
                        var productInfData = GsonUtils.getGson().fromJson(data, ProductInfoBean::class.java)
                        Log.e("===productInfData",GsonUtils.getGson().toJson(productInfData))
                        val code = productInfData.code
                        val productInfoList = productInfData.data
                        if (code == "0000" || code == "000") {
//                                productInfo = productInfoData?.firstOrNull()
                            Log.e("===productInfoData",GsonUtils.getGson().toJson(productInfoList))
                            productInfo = productInfoList?.get(0)
                            Log.e("===productInfo",GsonUtils.getGson().toJson(productInfo))
                            Log.e("===canAppLyNow",productInfo?.canApplyNow.toString())
                            val canApplyNowString = (productInfo?.canApplyNow).toString() + ""
                            val getCanApplyNowFromString = "\"canApplyNow\":1,"
                            val checkCanApplyNow = data.indexOf(getCanApplyNowFromString)
                            Log.e("---canAppLyNow", checkCanApplyNow.toString())
                            if (productInfo?.canApplyNow == 0 || canApplyNowString == "" || checkCanApplyNow == -1 ) {
                                showStatusTwo()
                            } else {
                                loangetLastUnpaidOffLoan()
                            }
                        } else if (TextUtils.equals(code, "3101")) {
                            toLogin()
                            EventBus.getDefault().post(UpdateLoanEvent(null))
                        }
                    }

                } catch (e: JSONException){
                    Log.e("----fromJsonError" ,e.toString())
                }


//                fatherActivity.hideMyLoading()
            }

            override fun onFaill(e: String) {
//                fatherActivity.hideMyLoading()
                showIndex()
            }

        })
    }
    fun mapStringToMap(str: String): Map<String, String>{
        var str1 = str.substring(1, str.length-1);
        var strs = str1.split(",");
        var map = mutableMapOf<String, String>()
        for (string in strs) {
            var key = string.split("=")[0];
            var value = string.split("=")[1];
            // 去掉头部空格
            var key1 = key.trim();
            var value1 = value.trim();
            map.put(key1, value1);
        }
        return map;
    }



    var dataBean: DataBean? = null
    private var lastLoanInfoVo: LoanInfoVo? = null
    private fun loangetLastUnpaidOffLoan() {

        if (userDataBean == null || StringUtils.isEmpty(userDataBean!!.token)) {
            return;
        }
        val params: MutableMap<String, String> = java.util.HashMap()
//        fatherActivity.showMyLoading()
        LoanModle().loangetLastUnpaidOffLoan(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                requireActivity().runOnUiThread {
                    try {
                        mLoanInfoVoList.clear()
                        lastLoanInfoVo = null;
                        dataBean = null;
                        var bean: LastLoanDetailBean =
                            GsonUtils.getGson().fromJson(data, LastLoanDetailBean::class.java)
                        LogUtils.logE("--loangetLastUnpaidOffLoan-3-bean:$bean")
                        if (bean != null) {
                            if (TextUtils.equals(bean.code, "000") || TextUtils.equals(
                                    bean.code,
                                    "0000"
                                )
                            ) {
                                dataBean = bean.data
                                showLoanInfo();
                                showIndex(3, true)
                                if (lastLoanInfoVo != null) {
                                    var status = lastLoanInfoVo!!.status
                                    var have = status == 2002 || status == 3001 || status == 3002 || status == 3003
                                    var day = TimeUtils.date2FormatDate(dataBean?.dueDate)
                                    if (day.isNullOrEmpty() || !have) {
                                        day = "*******"
                                    }
                                    var amount = dataBean?.totalSurplusAmount?.extFormatMoney()
                                    if (amount.isNullOrEmpty() || !have) {
                                        amount = "*******"
                                    }
                                    LogUtils.logE("kelvin -----day:$day, amount:$amount")
                                    val updateLoanBean = UpdateLoanBean(day, amount)
                                    EventBus.getDefault().post(UpdateLoanEvent(updateLoanBean))
                                } else {
                                    EventBus.getDefault().post(UpdateLoanEvent(null))
                                }



                                return@runOnUiThread
                            } else if (TextUtils.equals(bean.code, "3101")) {
//                                dataBean = null;
                                toLogin()
//                                showIndex(0, true)
                                EventBus.getDefault().post(UpdateLoanEvent(null))
                                return@runOnUiThread;
                            }
                        }
//                        dataBean = null;
//                        showIndex(1, true)
                        showIndex()
                        showIsLogin()
                        if (lastLoanInfoVo == null) {
                            if (!StringUtils.isEmpty(userDataBean!!.token)) {
                                lifecycleScope.launch(Dispatchers.Main){
                                    delay(1000)
                                    getCreditInfoForHomePage()
                                }
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    EventBus.getDefault().post(UpdateLoanEvent(null))
                }
//                fatherActivity.hideMyLoading()
            }

            override fun onFaill(e: String) {
                showIndex()
//                fatherActivity.hideMyLoading()
            }
        })
    }

    fun toLogin() {
        if (userDataBean == null) {
            return;
        }
        if (StringUtils.isEmpty(userDataBean!!.token)) {
            return;
        }
        userDataBean = null;
        SaveZiLiPageTool(getContextView()).puttKeyValue("user_info", "")
        ZiLiPageUserDataBean.setInstance(null);
        SPUtils.setPhone(null);
        val intent = Intent(context, LoginActivity::class.java)
        startActivity(intent)
        requireActivity().finish()
    }

    var mLoanInfoVoList: MutableList<LoanInfoVo> = ArrayList()

    private fun setMontoMoney() {
        var total = 0
        var minTotal = 0
        for (index in 0 until mLoanInfoVoList.size) {
            var item = mLoanInfoVoList.get(index)
            var status = item.status
            if (minTotal == 0 && (status == 2002 || status == 3001)){
                minTotal = item.currentPeriodTotalSurplusAmount.toInt();
            }
            if (item.isSelector) {
                total += item.currentPeriodTotalSurplusAmount.toInt()
            }
        }
        if (total == 0){
            total = minTotal;
        }
        val totalTx = StringUtils.formatNumberWithCommas(total.toString())
        Log.e("|||tv_money","8")
        tv_money.setText(totalTx)
    }

    private fun setOverdueMontoMoney() {
        var total = 0
        var minTotal = 0;
        for (index in 0 until mLoanInfoVoList.size) {
            var item = mLoanInfoVoList.get(index)
            var status = item.status
            if (status == 3002 || status == 3003){
                minTotal += item.currentPeriodTotalSurplusAmount.toInt();
            }
            if (item.isSelector) {
                total += item.currentPeriodTotalSurplusAmount.toInt()
            }
        }
        if (total == 0){
            total = minTotal;
        }
        val totalTx = StringUtils.formatNumberWithCommas(total.toString())
        Log.e("|||tv_money","9")
        tv_money.setText(totalTx)
    }

    private fun showLoanInfo() {
        Log.e("----isdataBean","----1")
        if (dataBean == null) {
            return;
        }
        Log.e("----dataBean", GsonUtils.getGson().toJson(dataBean))
        Log.e("----loanInfoVoList",GsonUtils.getGson().toJson(dataBean!!.loanInfoVoList))
        mLoanInfoVoList.clear()
        mLoanInfoVoList.addAll(dataBean!!.loanInfoVoList)
        var loanInfoVoList = dataBean!!.loanInfoVoList
        for (i in 0..loanInfoVoList.size - 1) {
            if (lastLoanInfoVo != null) {
                break
            }
            val infoVo = loanInfoVoList.get(i)
            if (infoVo != null) {
                val status: Int = infoVo.status
                when (status) {
                    1002, 2001, 2003, 2004, 2002, 3001, 3002 -> {
                        lastLoanInfoVo = infoVo
                    }
                }
            }
        }
        if (lastLoanInfoVo == null) {
            lastLoanInfoVo = loanInfoVoList.get(0)
        }

        var lastLoanInfoVodata = GsonUtils.getGson().toJson(lastLoanInfoVo)
        Log.e("===lastLoanInfoVo",lastLoanInfoVodata)
        if (lastLoanInfoVo != null) {
            var status = lastLoanInfoVo!!.status
//            var status = 3002
            moveable_quejas.visibility = View.GONE
            Log.e("----status",status.toString())
            when (status) {
                // Letter under review
                // Credit review failed
                0, 1001, 1004-> {
                    showStatusOne()
                }
                // Repayment in progress
                2002, 3001, 3003 -> {
                    showStatusFour()

                    if (dataBean!!.paymentId.isNullOrEmpty()) {
                        return
                    }
                    LogUtils.logE("home dataBean!!.paymentId->${dataBean!!.paymentId}")

                    var isShowMark = SharePreUtil.getStringData(dataBean!!.paymentId)
                    var isLoanOperation = SPUtils.getString("isLoanOperation")
                    LogUtils.logE("home isShowMark->$isShowMark, isLoanOperation->$isLoanOperation")
                    if (StringUtils.isEmpty(isShowMark) && isLoanOperation?.isNotEmpty() == true){
                        SharePreUtil.saveStringData(dataBean!!.paymentId, "true")
                        checkShowMark()
                    }
                }
                // Overdue
                3002, 3003 -> {
                    showStatusFive()
                }
                // Loan in progress
                1002, 2001, 2003, 2004 -> {
                    showStatusThree()
                }

                else -> {
                    showStatusTwo()
                }
            }
        }
    }

    private fun loadData() {

        val defaultStartDate = DateFormatUtils.formatTradeDate(getStartCalendar().getTime())
        val defaultEndDate = DateFormatUtils.formatTradeDate(getEndCalendar().getTime())

        val map: MutableMap<String, String> = java.util.HashMap()
        map["startDate"] =
            TimeUtils.date2LoanHistoryFormatDate(defaultStartDate.toString())
        map["endDate"] =
            TimeUtils.date2LoanHistoryFormatDate(defaultEndDate.toString())
        map["pageIndex"] = "1"
        LogUtils.logE("user loan request--->" + getGson().toJson(map))
        instant.getLoanList(map, object : HttpCallback {
            override fun onSuccess(data: String) {
                LogUtils.logE("user loan list >$data")
                val bean = Gson().fromJson(data, MyLoanListBean::class.java)
                for (i in bean.data.indices) {
                    Log.e("---sta", bean.data[i].paymentStatus)
                }
                realStatus = bean.data[0].paymentStatus

            }

            override fun onFaill(e: String) {
                LogUtils.logE("user loan request fail>$e")
            }
        })
    }

    private fun getStartCalendar(): Calendar {
        val currentTimeMillis = System.currentTimeMillis()
        val currentDate = Date(currentTimeMillis)
        val calendar = Calendar.getInstance()
        calendar.time = currentDate
        calendar.add(Calendar.MONTH, -2)
        return calendar
    }

    private fun getEndCalendar(): Calendar {
        val currentTimeMillis = System.currentTimeMillis()
        val currentDate = Date(currentTimeMillis)
        val calendar = Calendar.getInstance()
        calendar.time = currentDate
        return calendar
    }

    var appConfigBeanData: AppConfigBeanData? = null
    private fun securitygetApplicationConfig() {
        var params: HashMap<String, String> = HashMap()
//        fatherActivity.showMyLoading()
        mainModel?.securitygetApplicationConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                if (TextUtils.isEmpty(data)) return
                try {
                    var appConfigBean: AppConfigBean =
                        GsonUtils.getGson().fromJson(data, AppConfigBean::class.java);
                    if (appConfigBean != null) {
                        appConfigBeanData = appConfigBean?.data
                        SPUtils.put("smsCount",appConfigBeanData?.smsCount)
                        SPUtils.put("smsMaxCount",appConfigBeanData?.smsMaxCount)

                    }
                } catch (E: Exception) {
                    E.printStackTrace()
                }
//                fatherActivity.hideMyLoading()
            }

            override fun onFaill(e: String) {
//                fatherActivity.hideMyLoading()
            }

        })
    }


    private fun initPer(permission: String) {
        var phonePer = ContextCompat.checkSelfPermission(
            requireActivity(),
            Manifest.permission.READ_PHONE_STATE
        )
        var smsPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_SMS)
        var clPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_CALL_LOG)
        var cameraPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.CAMERA)

        if ( permission.equals("camera") ){
            if ((phonePer == PackageManager.PERMISSION_GRANTED) &&
                (smsPer == PackageManager.PERMISSION_GRANTED) &&
                (clPer == PackageManager.PERMISSION_GRANTED)
                && (cameraPer == PackageManager.PERMISSION_GRANTED)) {
                if (dataBean == null) {
                    utilsubInfo()
                }
            } else {
                showVeaEl("camera")
            }
        } else {
            if ((phonePer == PackageManager.PERMISSION_GRANTED) &&
                (smsPer == PackageManager.PERMISSION_GRANTED) &&
                (clPer == PackageManager.PERMISSION_GRANTED)) {
                if (dataBean == null) {
                    utilsubInfo()
                }
            } else {
                showVeaEl("")
            }
        }

    }

    private fun initPerForJustSub() {
        var phonePer = ContextCompat.checkSelfPermission(
            requireActivity(),
            Manifest.permission.READ_PHONE_STATE
        )
        var smsPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_SMS)
        var clPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_CALL_LOG)

        Log.e("----getPermissionForJustSubmit","getPermission")
        if ((phonePer == PackageManager.PERMISSION_GRANTED) &&
            (smsPer == PackageManager.PERMISSION_GRANTED) &&
            (clPer == PackageManager.PERMISSION_GRANTED)) {
            if (dataBean == null) {
                utilSubInfoWithNoOtherWork()
            }
        }
    }

    private fun showVeaEl(permission:String) {
        var tipsDialog = TipsPerDialog(
            requireContext(),
            "Vea el importe que puede solicitar ",
            "Después de otorgar los permisos podrás obtener el dinero de inmediato, date prisa en aplicar.",
            "Solicitalo ya"
        )
        tipsDialog.show()
        tipsDialog.setCallback(object : JDialogCallback {
            override fun cancel(view: View?) {

            }

            override fun confirm(view: View?) {
                if ( permission.equals("camera") ){
                    reqPer("camera")
                } else {
                    reqPer("")
                }

            }
        })
    }

    fun reqPer(permission: String) {
        var phonePer = ContextCompat.checkSelfPermission(
            requireActivity(),
            Manifest.permission.READ_PHONE_STATE
        )
        var smsPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_SMS)
        var clPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_CALL_LOG)
        var cameraPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.CAMERA)
        var readPer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_MEDIA_IMAGES)
        var writePer =
            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if ( permission.equals("camera") ){
            if ((cameraPer == PackageManager.PERMISSION_GRANTED)
//                &&
//                (readPer == PackageManager.PERMISSION_GRANTED) &&
//                (writePer == PackageManager.PERMISSION_GRANTED)
                ) {
                quejasGotoH5()
            } else {
                val permissions: MutableList<String> = ArrayList()
                permissions.add(Permission.CAMERA)
                permissions.add(Permission.READ_MEDIA_IMAGES)
                permissions.add(Permission.WRITE_EXTERNAL_STORAGE)
                val permissionStr = arrayOf(
                    Manifest.permission.CAMERA, Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                activity?.let { ActivityCompat.requestPermissions(it, permissionStr, 10001) }
                XXPermissions.with(this).permission(permissions).request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (allGranted) {
                            quejasGotoH5()
                        } else {
                            showRequestPer()
                        }
                    }

                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                        super.onDenied(permissions, doNotAskAgain)
                        showRequestPer()
                    }

                })
            }
        } else {
            if ((phonePer == PackageManager.PERMISSION_GRANTED)
                && (smsPer == PackageManager.PERMISSION_GRANTED)
                && (clPer == PackageManager.PERMISSION_GRANTED)) {
                if (dataBean == null) {
                    utilsubInfo()
                }
            } else {
                val permissions: MutableList<String> = ArrayList()
                permissions.add(Permission.READ_SMS)
                permissions.add(Permission.READ_CALL_LOG)
                permissions.add(Permission.READ_PHONE_STATE)
                XXPermissions.with(this).permission(permissions).request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (allGranted) {
                            if (dataBean == null) {
                                utilsubInfo()
                            }
                        } else {
                            showRequestPer()
                        }
                    }

                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                        super.onDenied(permissions, doNotAskAgain)
                        showRequestPer()
                    }

                })
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            101 -> {
                var accepted = true
                var i = 0
                while (i < grantResults.size) {
                    val acceptedTmp = grantResults[i] == PackageManager.PERMISSION_GRANTED
                    if (!acceptedTmp) {
                        accepted = false
                    }
                    i++
                }
                if (accepted) {
                    if (dataBean == null) {
                        utilsubInfo()
                    }
                } else {
                    showRequestPer();
                }
            }
        }
    }

    private fun showRequestPer() {

        if (tipsPerLineDialog != null) {
            if (!tipsPerLineDialog?.isShowing!!) {
                tipsPerLineDialog?.show()
            }
        }

        tipsPerLineDialog?.setCallback(object : JDialogCallback {
            override fun cancel(view: View?) {
            }

            override fun confirm(view: View?) {
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", requireActivity().packageName, null)
                intent.data = uri
                startActivity(intent)
            }
        })

    }

    fun securitygetBannerConfig() {
        var params: HashMap<String, String> = HashMap()
        params["bannerType"] = "2"
        params["hasAppH5"] = "0"
        params["pageType"] = "1"
//        fatherActivity.showMyLoading()
        mainModel.securitygetBannerConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                if (TextUtils.isEmpty(data)) return
                try {
                    requireActivity().runOnUiThread {
                        bannerList.clear()
                        var bannerDataBean =
                            GsonUtils.getGson().fromJson(data, BannerDataBean::class.java)
                        if (bannerDataBean != null) {
                            var listTmp = bannerDataBean.data
                            if (listTmp != null) {
                                bannerList.addAll(listTmp);
                            }

                        }
                        view_pager.adapter?.notifyDataSetChanged()
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
//                fatherActivity.hideMyLoading()
            }

            override fun onFaill(e: String) {
//                fatherActivity.hideMyLoading()
            }

        })
    }


    private fun getZiLiPageUserFullInfo() {
        try {
            val params: MutableMap<String, String> = java.util.HashMap()
            params["custId"] = ZiLiPageUserDataBean.getInstance().customerId
//            fatherActivity.showMyLoading()
            KycModle().getZiLiPageUserFullInfo(params, object : HttpCallback {
                override fun onSuccess(data: String) {
                    requireActivity().runOnUiThread {
                        try {
                            val jsonObject = JSONObject(data)
                            LogUtils.logE("history msg>$jsonObject")
                            if (KycModle().isSuccess(jsonObject)) {
                                val dataJSONObject = jsonObject.optJSONObject("data")
                                if (dataJSONObject != null) {
                                    ZiLiPageUserDataBean.getInstance().mobile =
                                        dataJSONObject.optString("mobile")
                                    webPhone = dataJSONObject.optString("mobile")
                                    SharePreUtil.saveStringData("webPhone", webPhone)
                                    ZiLiPageUserDataBean.getInstance().lastName =
                                        dataJSONObject.optString("lastName")
                                    webName = dataJSONObject.optString("lastName")
                                    SharePreUtil.saveStringData("webName", webName)
                                }
                            }
                        } catch (e: java.lang.Exception) {
                            e.printStackTrace()
                        }
                    }
//                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
//                    fatherActivity.hideMyLoading()
                }
            })
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    var markDialog: MarkDialog? = null
    private fun showMark(){
        if (markDialog != null){
            if (markDialog!!.isShowing){
                return;
            }
        }
        markDialog = MarkDialog(requireActivity())
        markDialog?.show()
    }

    private fun checkShowMark() {
        val params: MutableMap<String, String> = java.util.HashMap()
        params.put("pageIndex","1")
        params.put("pageSize", "20")
//        fatherActivity.showMyLoading()
        PermisosModle.instant.getLoanList(params, object : HttpCallback{
            override fun onSuccess(data: String) {
                val bean = Gson().fromJson(data, MyLoanListBean::class.java)
                if (bean.code == "0000"){
                    LogUtils.logE("home ---bean.data.size>${bean.data.size}")
                    if (bean.data.isNotEmpty() && bean.data.size >= 2) {
                        var isShow = true
                        bean.data.forEach { dataBean ->
                            LogUtils.logE("home ---for paymentStatus>${dataBean.paymentStatus}")
                            if (dataBean.paymentStatus == "3002" || dataBean.paymentStatus == "3003") {
                                isShow = false
                            }
                        }
                        if (isShow) {
                            requireActivity().runOnUiThread{
                                showMark()
                            }
                        }
                    }
                }
//                fatherActivity.hideMyLoading()
            }

            override fun onFaill(e: String) {
//                fatherActivity.hideMyLoading()
            }

        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        Log.e("----","onActivityResult")
        if (requestCode == REQUEST_INFO_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val showPer: Boolean? = data?.getBooleanExtra("showPer", false)
                if (showPer == true) {
                    if (TextUtils.equals(userDataBean!!.rewrite, "N")){
                        if (dataBean == null) {
                            lifecycleScope.launch(Dispatchers.Main){
                                delay(1000)
                                initPer("")
                            }
                        }
                    }
                }
            }
        }
    }
}